package com.wg.db.repository.code;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 异步MySQL仓库（List存储版）
 *
 * @param <Key> 实体ID类型
 * @param <T>   实体类型
 */
public class MySqlAsyncListRepository<Key extends Serializable, T> extends AbstractMySqlAsyncRepository<Key, T> {
    private final LinkedList<DataWrapper<Key, T>> dataList = new LinkedList<>();

    public MySqlAsyncListRepository(Class<T> entityClass) {
        super(entityClass);
    }

    @Override
    public int pendingSize() {
        return dataList.size();
    }

    @Override
    protected void addDataWrapper(DataWrapper<Key, T> dataWrapper) {
        dataList.add(dataWrapper);
    }

    @Override
    protected List<DataWrapper<Key, T>> getAllEntities() {
        List<DataWrapper<Key, T>> currentBatch;
        if (dataList.size() <= batchSize) {
            currentBatch = new ArrayList<>(dataList);
            dataList.clear();
        } else {
            currentBatch = new ArrayList<>(batchSize);
            for (int i = 0; i < batchSize; i++) {
                currentBatch.add(dataList.removeFirst());
            }
        }
        return currentBatch;
    }

    @Override
    protected void onSuccess(List<DataWrapper<Key, T>> successDatas) {
    }

    @Override
    protected void onFail(List<DataWrapper<Key, T>> failDatas) {
        for (DataWrapper<Key, T> dataWrapper : failDatas) {
            dataList.addFirst(dataWrapper);
        }
    }
}